<template>
  <section class="todoapp">
    <HmHeader @addList="addList"></HmHeader>

    <HmBody
      :list="rederList"
      @delList="delList"
      @changeList="changeList"
      @changeAll="changeAll"
    ></HmBody>

    <HmFoor
      :sum="sum"
      @delAll="delAll"
      :isShow="isShow"
      :type="type"
      @changeBtn="changeBtn"
    ></HmFoor>
  </section>
</template>

<script>
import HmHeader from "./components/HmHeader.vue";
import HmBody from "./components/HmBody.vue";
import HmFoor from "./components/HmFoor.vue";
export default {
  // 注册组件
  components: {
    HmHeader,
    HmBody,
    HmFoor,
  },
  // 数据
  data() {
    return {
      list: JSON.parse(localStorage.getItem("list")) || [
        {
          id: 1,
          value: "吃",
          flag: false,
        },
        {
          id: 2,
          value: "睡",
          flag: true,
        },
        {
          id: 3,
          value: "玩",
          flag: false,
        },
      ],
      type: "all",
    };
  },

  methods: {
    // 添加
    addList(value) {
      this.list = [
        {
          id: +new Date(),
          value,
          flag: false,
        },
        ...this.list,
      ];
    },
    // 删除
    delList(id) {
      const event = this.list.find((item) => item.id === id);

      if (event.flag === false) return alert("不要");

      this.list = this.list.filter((item) => item.id !== id);
    },
    // 修改状态
    changeList(flag, id) {
      this.list.forEach((item) => {
        if (item.id === id) {
          item.flag = flag;
        }
      });
    },
    // 清除所有
    delAll() {
      this.list = this.list.filter((item) => !item.flag);
    },
    // 点击切换type
    changeBtn(value) {
      // console.log(value);
      this.type = value;
    },
    // 全选
    changeAll(flag) {
      this.list.forEach((item) => (item.flag = flag));
    },
  },
  computed: {
    // 计算属性剩余
    sum() {
      return this.list.filter((item) => !item.flag).length;
    },
    //  隐藏清除已完成
    isShow() {
      return this.list.some((item) => item.flag);
    },

    rederList() {
      switch (this.type) {
        case "all":
          return this.list;
        case "active":
          return this.list.filter((item) => !item.flag);
        case "completed":
          return this.list.filter((item) => item.flag);
        default:
          return this.list;
      }
    },
  },

  // 监听
  watch: {
    list: {
      handler(newVal) {
        localStorage.setItem("list", JSON.stringify(newVal));
      },
      deep: true,
      immediate: true,
    },
  },
};
</script>

<style></style>
